package demo.zzz.com.captureactivity;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.List;

public class MainActivity extends AppCompatActivity{
    private static final String TAG="MainActivity";

    private static final int REQUEST_CODE=7;
    private static final int SCAN_REQUEST_CODE = 100;

    private String mSealData = null;
    private Button hello,helloReview,simpleZxing,YZxing;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );
        //这个是一片枫叶集成
        hello = findViewById( R.id.hello );
        hello.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission( MainActivity.this, Manifest.permission.CAMERA ) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions( MainActivity.this, new String[]{Manifest.permission.CAMERA}, 1 );
                }else {
                    // Have gotten the permission
                    startCaptureActivityForResult();
                }
            }
        } );
        //这个是一片枫叶自定义
        helloReview = findViewById( R.id.helloReview );
        helloReview.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent  intent = new Intent(MainActivity.this, helloReviewActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
            }
        } );
        

        //这个是最初的
        simpleZxing = findViewById( R.id.simpleZxing );
        simpleZxing.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent_scan=new Intent( MainActivity.this, simpleZxingActivity.class );
                startActivity( intent_scan );
            }
        } );

        //
        YZxing = findViewById( R.id.YZxing );
        YZxing.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {


            }
        } );



    }


    private void startCaptureActivityForResult() {
    Intent intent_scan=new Intent( MainActivity.this, CaptureActivity.class );
    startActivityForResult( intent_scan, REQUEST_CODE );


}


    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult( requestCode, permissions, grantResults );
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startCaptureActivityForResult();
                } else {
                    Toast.makeText( MainActivity.this, "拒绝", Toast.LENGTH_LONG ).show();
                }
            default:
                break;
        }

    }

    // 扫码onActivityResult
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode ==REQUEST_CODE) {
            Log.e( TAG, "onActivityResult: " + requestCode + "data:" + data );
            if (data == null) {
                Toast.makeText( MainActivity.this, "扫描二维码失败!", Toast.LENGTH_LONG ).show();
            }else {
                Bundle bundle = data.getExtras();
                Log.e( TAG, "Bundle: " + bundle  );
                if (bundle == null) {
                    Toast.makeText( MainActivity.this, "请重新扫描二维码!", Toast.LENGTH_LONG ).show();
                    return;
                }
                if (bundle.getInt( CodeUtils.RESULT_TYPE ) == CodeUtils.RESULT_SUCCESS) {
                    //这是拿到解析扫描到的信息，并转成字符串
                    mSealData = bundle.getString( CodeUtils.RESULT_STRING );  //or do sth
                    Log.e( TAG, "onActivityResult: " + recode(mSealData) );
                    //这里加一个弹框提示显示铅封号
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setCancelable( false );
                    builder.setTitle("提示")
                            .setMessage("铅封号：" + recode(mSealData))
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            })
                            .setNegativeButton( "取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            } )
                            .create().show();


                } else if (bundle.getInt( CodeUtils.RESULT_TYPE ) == CodeUtils.RESULT_FAILED) {
                    //否则提示解析二维码失败
                    Toast.makeText( MainActivity.this, "解析二维码失败!", Toast.LENGTH_LONG ).show();

                }
            }
        }

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SCAN_REQUEST_CODE) {
                //Todo Handle the isbn number entered manually
                String isbn = data.getStringExtra("CaptureIsbn");
                if (!TextUtils.isEmpty(isbn)) {
                    //todo something
                    
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setCancelable( false );
                    builder.setTitle("提示")
                            .setMessage("铅封号：" + recode(isbn))
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            })
                            .setNegativeButton( "取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            } )
                            .create().show();
                    if (isbn.contains("http")) {
                        Intent intent = new Intent(this, WebViewActivity.class);
                        intent.putExtra(WebViewActivity.RESULT, isbn);
                        startActivity(intent);
                    }
                }
            }
        }


//        switch (requestCode) {
//            case CaptureActivity.REQ_CODE:
//                mSealData = data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT);
//                switch (resultCode) {
//                    case RESULT_OK:
//                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//                        builder.setCancelable( false );
//                        builder.setTitle("提示")
//                                .setMessage("铅封号：" + recode(mSealData))
//                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//
//                                    }
//                                })
//                                .setNegativeButton( "取消", new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//
//                                    }
//                                } )
//                                .create().show();
//                        break;
//                    case RESULT_CANCELED:
//                        if (data != null) {
//                            // for some reason camera is not working correctly
//                            Log.d(TAG,data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT));
//                        }
//                        break;
//                }
//                break;
//        }

    }

    //防止二维码扫描中文乱码
    private String recode(String str) {
        String formart = "";

        try {
            boolean ISO = Charset.forName("ISO-8859-1").newEncoder()
                    .canEncode(str);
            if (ISO) {
                formart = new String(str.getBytes("ISO-8859-1"), "GB2312");
            } else {
                formart = str;
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return formart;
    }

}
